package com.ghsc.ghxc.jsb.ui.message.view.gif

import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.GridLayoutManager
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentPwLiveGiftBinding
import com.ghsc.ghxc.jsb.ui.live.bean.GifDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.GifResultDataBean
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusGifAttachment
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdPopViiew
import com.ghsc.ghxc.jsb.ui.message.view.gif.adapter.GifListAdapter
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.msg.model.IMMessage
import com.netease.yunxin.kit.chatkit.repo.ChatRepo
import com.netease.yunxin.kit.chatkit.ui.common.MessageHelper
import com.netease.yunxin.kit.corekit.im.provider.FetchCallbackImpl

/**
 * 项目：GuoHuaMall
 * 包名：com.ghsc.ghxc.ui.live.view.gif
 * 类名：GiftFragment
 * 创建时间：2023/9/14 22:37
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class ImGiftFragment : BaseVMFragment<ImGiftViewModel, FragmentPwLiveGiftBinding>(R.layout.fragment_pw_live_gift) {
    override fun attachVMClass(): Class<ImGiftViewModel>? {
        return ImGiftViewModel::class.java
    }
    override fun lazyLoad() {
    }
    //id
    private var accountId:String =""


    var userResultBean: GifResultDataBean? = null


    companion object {
        fun newInstance(accountId:String): ImGiftFragment {
            val fragment = ImGiftFragment()
            fragment.accountId = accountId
            return fragment
        }
    }

    //赠送礼物回调  暂时没有用到
    private var listener:((id:Int,count:Int,isBackpack:Boolean) -> Unit)? = null
    //弹框关闭回调
    private var dismiss:(() -> Unit)? = null
    fun setOnGiveGiftResultListener(listener: ((id:Int,count:Int,isBackpack:Boolean) -> Unit)){
        this.listener = listener
    }
    fun setOnDismissListener(listener: (() -> Unit)){
        this.dismiss = listener
    }



    var price:Double=0.0
    var gid:String= ""
    var gifTitle:String= ""
    var gifImg:String =""
    var downurl :String=""

    var mList: MutableList<GifDataBean> = ArrayList()
    val mAdapter: GifListAdapter by lazy { GifListAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = GridLayoutManager(this.context, 4)
        binding.rvList.adapter =mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            for (i in mAdapter.data.indices) {
                if (i == position) {
                    mAdapter.data[i].isCheck = true
                    loge("选择的礼物name="+mAdapter.data[i].name+"id="+mAdapter.data[i].gid.toString() +"img="+mAdapter.data[i].images+"url="+mAdapter.data[i].downurl)
                    gifTitle=mAdapter.data[i].name
                    gifImg=mAdapter.data[i].images
                    price=mAdapter.data[i].price.toDouble()
                    if (!TextUtils.isEmpty(mAdapter.data[i].downurl))
                        downurl=mAdapter.data[i].downurl
                    else
                        downurl= ""
                    gid=mAdapter.data[i].gid.toString()

                } else {
                    mAdapter.data[i].isCheck = false
                }
            }
            mAdapter.notifyDataSetChanged()
        }
        //请求礼物列表数据
        mViewModel.onGetGifListMethod("")

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.tvAl.setSingleClickListener {
            dismiss?.invoke()
        }
        binding.btnNext.setSingleClickListener {
            if (!TextUtils.isEmpty(gid)){
                userResultBean?.let {
                    loge("当前"+it.jifen+"xxxx==="+price)
                    if (userResultBean!!.jifen>price){
                        XPopup.Builder(requireActivity())
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                            .customHostLifecycle(lifecycle)
                            .autoOpenSoftInput(true)
                            .moveUpToKeyboard(true)
                            .dismissOnTouchOutside(false)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            .asCustom(
                                PayPwdPopViiew(requireActivity(),object :
                                    PayPwdPopViiew.SublickListener{
                                    override fun onAdopt( pwdStr: String) {
                                        //送礼物
                                        val map: HashMap<String, Any> = HashMap()
                                        map["gid"] = gid
                                        map["tuid"] = accountId
                                        map["cnt"] =  1
                                        map["paypassword"] =pwdStr
                                        val json=  GsonUtil.mapToJsonStrObjEncryption(map)
                                        loge("送的礼物="+map.toString())
                                        mViewModel.onToGifMethod(json!!)
                                    }
                                })
                            )
                            .show()
                    }else{
                        showToast("余额不足啦")
                    }
                }
            }else showToast("请选择礼物喔")
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ImGiftFragment) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@ImGiftFragment) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onToGifData.observe(this@ImGiftFragment){
                //送礼物成功
                binding.hongbao.text=it.data.data.jifen.toString()

                // 以单聊类型为例
                val sessionType = SessionTypeEnum.P2P
                val custBean = CusGifAttachment()
                custBean. gid=gid.toInt()
                custBean. name=gifTitle
                custBean. images=gifImg
                custBean. price=price
                custBean. downurl=downurl
                custBean. cnt=1
                custBean. txid=it.data.data.txid
                custBean. uid= it.data.data.uid
                custBean. tuid=it.data.data.tuid
                loge("xxxx==="+custBean.toString())
//                            // 创建一个自定义消息
                val custMsg = MessageBuilder.createCustomMessage(it.data.data.tuid,sessionType,custBean)


                ChatRepo.sendMessage(
                    custMsg,
                    false,
                    object : FetchCallbackImpl<Void>() {
                        override fun onFailed(code: Int) {
                        }
                    })

                // 发送给对方
//                NIMClient.getService(MsgService::class.java).sendMessage(custMsg, true)
//                    .setCallback(object : RequestCallback<Void> {
//                        override fun onSuccess(result: Void?) {
//                            showToast("发送了一个礼物...")
////                            NIMClient.getService(MsgService::class.java)
////                                .updateIMMessageStatus(custMsg, true)
//                                //刷新ui效果
//
//
//                        }
//
//                        override fun onFailed(code: Int) {
//                        }
//
//                        override fun onException(exception: Throwable?) {
//                        }
//
//                    })


            }
            onGetGifListData.observe(this@ImGiftFragment){
                userResultBean=it.data.data
                binding.hongbao.text=it.data.data.jifen.toString()
                mAdapter.replaceData(it.data.list)
            }
        }
    }

}